home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_perl.idb / usr / freeware / catman / u_man / cat1 / perlcall.Z / perlcall
Encoding:
Text File  |  1998-10-28  |  77.5 KB  |  2,509 lines

  1.  
  2.  
  3.  
  4.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  5.  
  6.  
  7.  
  8.      NNNNAAAAMMMMEEEE
  9.       perlcall - Perl calling conventions from C
  10.  
  11.      DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.       The purpose of this document is to show you how to call Perl
  13.       subroutines directly from C, i.e., how to write _c_a_l_l_b_a_c_k_s.
  14.  
  15.       Apart    from discussing    the C interface    provided by Perl for
  16.       writing callbacks the    document uses a    series of examples to
  17.       show how the interface actually works    in practice.  In
  18.       addition some    techniques for coding callbacks    are covered.
  19.  
  20.       Examples where callbacks are necessary include
  21.  
  22.       +o An Error Handler
  23.            You have    created    an XSUB    interface to an    application's
  24.            C API.
  25.  
  26.            A fairly    common feature in applications is to allow you
  27.            to define a C function that will    be called whenever
  28.            something nasty occurs. What we would like is to    be
  29.            able to specify a Perl subroutine that will be called
  30.            instead.
  31.  
  32.       +o An Event Driven Program
  33.            The classic example of where callbacks are used is when
  34.            writing an event    driven program like for    an X windows
  35.            application.  In    this case you register functions to be
  36.            called whenever specific    events occur, e.g., a mouse
  37.            button is pressed, the cursor moves into    a window or a
  38.            menu item is selected.
  39.  
  40.       Although the techniques described here are applicable    when
  41.       embedding Perl in a C    program, this is not the primary goal
  42.       of this document.  There are other details that must be
  43.       considered and are specific to embedding Perl. For details
  44.       on embedding Perl in C refer to the _p_e_r_l_e_m_b_e_d    manpage.
  45.  
  46.       Before you launch yourself head first    into the rest of this
  47.       document, it would be    a good idea to have read the following
  48.       two documents    - the _p_e_r_l_x_s manpage and the _p_e_r_l_g_u_t_s manpage.
  49.  
  50.      TTTTHHHHEEEE PPPPEEEERRRRLLLL____CCCCAAAALLLLLLLL FFFFUUUUNNNNCCCCTTTTIIIIOOOONNNNSSSS
  51.       Although this    stuff is easier    to explain using examples, you
  52.       first    need be    aware of a few important definitions.
  53.  
  54.       Perl has a number of C functions that    allow you to call Perl
  55.       subroutines.    They are
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.      Page 1                        (printed 10/23/98)
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  71.  
  72.  
  73.  
  74.           I32 perl_call_sv(SV* sv, I32 flags) ;
  75.           I32 perl_call_pv(char *subname, I32 flags) ;
  76.           I32 perl_call_method(char    *methname, I32 flags) ;
  77.           I32 perl_call_argv(char *subname,    I32 flags, register char **argv) ;
  78.  
  79.       The key function is _p_e_r_l__c_a_l_l__s_v.  All the other functions
  80.       are fairly simple wrappers which make    it easier to call Perl
  81.       subroutines in special cases.    At the end of the day they
  82.       will all call    _p_e_r_l__c_a_l_l__s_v to    invoke the Perl    subroutine.
  83.  
  84.       All the _p_e_r_l__c_a_l_l_* functions    have a flags parameter which
  85.       is used to pass a bit    mask of    options    to Perl.  This bit
  86.       mask operates    identically for    each of    the functions.    The
  87.       settings available in    the bit    mask are discussed in the
  88.       section on _F_L_A_G _V_A_L_U_E_S.
  89.  
  90.       Each of the functions    will now be discussed in turn.
  91.  
  92.       ppppeeeerrrrllll____ccccaaaallllllll____ssssvvvv
  93.            _p_e_r_l__c_a_l_l__s_v takes two parameters, the first, sv, is an
  94.            SV*.  This allows you to    specify    the Perl subroutine to
  95.            be called either    as a C string (which has first been
  96.            converted to an SV) or a    reference to a subroutine. The
  97.            section,    _U_s_i_n_g _p_e_r_l__c_a_l_l__s_v, shows how you can make use
  98.            of _p_e_r_l__c_a_l_l__s_v.
  99.  
  100.       ppppeeeerrrrllll____ccccaaaallllllll____ppppvvvv
  101.            The function, _p_e_r_l__c_a_l_l__p_v, is similar to _p_e_r_l__c_a_l_l__s_v
  102.            except it expects its first parameter to    be a C char*
  103.            which identifies    the Perl subroutine you    want to    call,
  104.            e.g., perl_call_pv("fred", 0).  If the subroutine you
  105.            want to call is in another package, just    include    the
  106.            package name in the string, e.g., "pkg::fred".
  107.  
  108.       ppppeeeerrrrllll____ccccaaaallllllll____mmmmeeeetttthhhhoooodddd
  109.            The function _p_e_r_l__c_a_l_l__m_e_t_h_o_d is    used to    call a method
  110.            from a Perl class.  The parameter methname corresponds
  111.            to the name of the method to be called.    Note that the
  112.            class that the method belongs to    is passed on the Perl
  113.            stack rather than in the    parameter list.    This class can
  114.            be either the name of the class (for a static method)
  115.            or a reference to an object (for    a virtual method).
  116.            See the _p_e_r_l_o_b_j manpage for more    information on static
  117.            and virtual methods and the section on _U_s_i_n_g
  118.            _p_e_r_l__c_a_l_l__m_e_t_h_o_d    for an example of using
  119.            _p_e_r_l__c_a_l_l__m_e_t_h_o_d.
  120.  
  121.       ppppeeeerrrrllll____ccccaaaallllllll____aaaarrrrggggvvvv
  122.            _p_e_r_l__c_a_l_l__a_r_g_v calls the    Perl subroutine    specified by
  123.            the C string stored in the subname parameter. It    also
  124.            takes the usual flags parameter.     The final parameter,
  125.            argv, consists of a NULL    terminated list    of C strings
  126.  
  127.  
  128.  
  129.      Page 2                        (printed 10/23/98)
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  137.  
  138.  
  139.  
  140.            to be passed as parameters to the Perl subroutine.  See
  141.            _U_s_i_n_g _p_e_r_l__c_a_l_l__a_r_g_v.
  142.  
  143.       All the functions return an integer. This is a count of the
  144.       number of items returned by the Perl subroutine. The actual
  145.       items    returned by the    subroutine are stored on the Perl
  146.       stack.
  147.  
  148.       As a general rule you    should _a_l_w_a_y_s check the    return value
  149.       from these functions.     Even if you are expecting only    a
  150.       particular number of values to be returned from the Perl
  151.       subroutine, there is nothing to stop someone from doing
  152.       something unexpected - don't say you haven't been warned.
  153.  
  154.      FFFFLLLLAAAAGGGG VVVVAAAALLLLUUUUEEEESSSS
  155.       The flags parameter in all the _p_e_r_l__c_a_l_l_* functions is a
  156.       bit mask which can consist of    any combination    of the symbols
  157.       defined below, OR'ed together.
  158.  
  159.       GGGG____VVVVOOOOIIIIDDDD
  160.  
  161.       Calls    the Perl subroutine in a void context.
  162.  
  163.       This flag has    2 effects:
  164.  
  165.       1.   It indicates to the subroutine being called that    it is
  166.            executing in a void context (if it executes _w_a_n_t_a_r_r_a_y
  167.            the result will be the undefined    value).
  168.  
  169.       2.   It ensures that nothing is actually returned from the
  170.            subroutine.
  171.  
  172.       The value returned by    the _p_e_r_l__c_a_l_l_*    function indicates how
  173.       many items have been returned    by the Perl subroutine - in
  174.       this case it will be 0.
  175.  
  176.       GGGG____SSSSCCCCAAAALLLLAAAARRRR
  177.  
  178.       Calls    the Perl subroutine in a scalar    context.  This is the
  179.       default context flag setting for all the _p_e_r_l__c_a_l_l_*
  180.       functions.
  181.  
  182.       This flag has    2 effects:
  183.  
  184.       1.   It indicates to the subroutine being called that    it is
  185.            executing in a scalar context (if it executes _w_a_n_t_a_r_r_a_y
  186.            the result will be false).
  187.  
  188.       2.   It ensures that only a scalar is    actually returned from
  189.            the subroutine.    The subroutine can, of course,    ignore
  190.            the _w_a_n_t_a_r_r_a_y and return    a list anyway. If so, then
  191.            only the    last element of    the list will be returned.
  192.  
  193.  
  194.  
  195.      Page 3                        (printed 10/23/98)
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  203.  
  204.  
  205.  
  206.       The value returned by    the _p_e_r_l__c_a_l_l_*    function indicates how
  207.       many items have been returned    by the Perl subroutine - in
  208.       this case it will be either 0    or 1.
  209.  
  210.       If 0,    then you have specified    the G_DISCARD flag.
  211.  
  212.       If 1,    then the item actually returned    by the Perl subroutine
  213.       will be stored on the    Perl stack - the section _R_e_t_u_r_n_i_n_g _a
  214.       _S_c_a_l_a_r shows how to access this value    on the stack.
  215.       Remember that    regardless of how many items the Perl
  216.       subroutine returns, only the last one    will be    accessible
  217.       from the stack - think of the    case where only    one value is
  218.       returned as being a list with    only one element.  Any other
  219.       items    that were returned will    not exist by the time control
  220.       returns from the _p_e_r_l__c_a_l_l_* function.  The section
  221.       _R_e_t_u_r_n_i_n_g _a _l_i_s_t _i_n _a    _s_c_a_l_a_r _c_o_n_t_e_x_t shows an    example    of
  222.       this behavior.
  223.  
  224.       GGGG____AAAARRRRRRRRAAAAYYYY
  225.  
  226.       Calls    the Perl subroutine in a list context.
  227.  
  228.       As with G_SCALAR, this flag has 2 effects:
  229.  
  230.       1.   It indicates to the subroutine being called that    it is
  231.            executing in an array context (if it executes _w_a_n_t_a_r_r_a_y
  232.            the result will be true).
  233.  
  234.       2.   It ensures that all items returned from the subroutine
  235.            will be accessible when control returns from the
  236.            _p_e_r_l__c_a_l_l_* function.
  237.  
  238.       The value returned by    the _p_e_r_l__c_a_l_l_*    function indicates how
  239.       many items have been returned    by the Perl subroutine.
  240.  
  241.       If 0,    then you have specified    the G_DISCARD flag.
  242.  
  243.       If not 0, then it will be a count of the number of items
  244.       returned by the subroutine. These items will be stored on
  245.       the Perl stack.  The section _R_e_t_u_r_n_i_n_g _a _l_i_s_t    _o_f _v_a_l_u_e_s
  246.       gives    an example of using the    G_ARRAY    flag and the mechanics
  247.       of accessing the returned items from the Perl    stack.
  248.  
  249.       GGGG____DDDDIIIISSSSCCCCAAAARRRRDDDD
  250.  
  251.       By default, the _p_e_r_l__c_a_l_l_* functions    place the items
  252.       returned from    by the Perl subroutine on the stack.  If you
  253.       are not interested in    these items, then setting this flag
  254.       will make Perl get rid of them automatically for you.     Note
  255.       that it is still possible to indicate    a context to the Perl
  256.       subroutine by    using either G_SCALAR or G_ARRAY.
  257.  
  258.  
  259.  
  260.  
  261.      Page 4                        (printed 10/23/98)
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  269.  
  270.  
  271.  
  272.       If you do not    set this flag then it is _v_e_r_y important    that
  273.       you make sure    that any temporaries (i.e., parameters passed
  274.       to the Perl subroutine and values returned from the
  275.       subroutine) are disposed of yourself.     The section _R_e_t_u_r_n_i_n_g
  276.       _a _S_c_a_l_a_r gives details of how    to dispose of these
  277.       temporaries explicitly and the section _U_s_i_n_g _P_e_r_l _t_o _d_i_s_p_o_s_e
  278.       _o_f _t_e_m_p_o_r_a_r_i_e_s discusses the specific    circumstances where
  279.       you can ignore the problem and let Perl deal with it for
  280.       you.
  281.  
  282.       GGGG____NNNNOOOOAAAARRRRGGGGSSSS
  283.  
  284.       Whenever a Perl subroutine is    called using one of the
  285.       _p_e_r_l__c_a_l_l_* functions, it is assumed by default that
  286.       parameters are to be passed to the subroutine.  If you are
  287.       not passing any parameters to    the Perl subroutine, you can
  288.       save a bit of    time by    setting    this flag.  It has the effect
  289.       of not creating the @_ array for the Perl subroutine.
  290.  
  291.       Although the functionality provided by this flag may seem
  292.       straightforward, it should be    used only if there is a    good
  293.       reason to do so.  The    reason for being cautious is that even
  294.       if you have specified    the G_NOARGS flag, it is still
  295.       possible for the Perl    subroutine that    has been called    to
  296.       think    that you have passed it    parameters.
  297.  
  298.       In fact, what    can happen is that the Perl subroutine you
  299.       have called can access the @_    array from a previous Perl
  300.       subroutine.  This will occur when the    code that is executing
  301.       the _p_e_r_l__c_a_l_l_* function has itself been called from another
  302.       Perl subroutine. The code below illustrates this
  303.  
  304.           sub fred
  305.         { print    "@_\n"    }
  306.  
  307.           sub joe
  308.         { &fred    }
  309.  
  310.           &joe(1,2,3) ;
  311.  
  312.       This will print
  313.  
  314.           1    2 3
  315.  
  316.       What has happened is that fred accesses the @_ array which
  317.       belongs to joe.
  318.  
  319.       GGGG____EEEEVVVVAAAALLLL
  320.  
  321.       It is    possible for the Perl subroutine you are calling to
  322.       terminate abnormally,    e.g., by calling _d_i_e explicitly    or by
  323.       not actually existing.  By default, when either of these
  324.  
  325.  
  326.  
  327.      Page 5                        (printed 10/23/98)
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  335.  
  336.  
  337.  
  338.       events occurs, the process will terminate immediately.  If
  339.       you want to trap this    type of    event, specify the G_EVAL
  340.       flag.     It will put an    _e_v_a_l { } around    the subroutine call.
  341.  
  342.       Whenever control returns from    the _p_e_r_l__c_a_l_l_*    function you
  343.       need to check    the $@ variable    as you would in    a normal Perl
  344.       script.
  345.  
  346.       The value returned from the _p_e_r_l__c_a_l_l_* function is
  347.       dependent on what other flags    have been specified and
  348.       whether an error has occurred.  Here are all the different
  349.       cases    that can occur:
  350.  
  351.       +o    If the _p_e_r_l__c_a_l_l_* function returns normally, then the
  352.            value returned is as specified in the previous
  353.            sections.
  354.  
  355.       +o    If G_DISCARD is specified, the return value will    always
  356.            be 0.
  357.  
  358.       +o    If G_ARRAY is specified _a_n_d an error has    occurred, the
  359.            return value will always    be 0.
  360.  
  361.       +o    If G_SCALAR is specified    _a_n_d an error has occurred, the
  362.            return value will be 1 and the value on the top of the
  363.            stack will be _u_n_d_e_f. This means that if you have
  364.            already detected    the error by checking $@ and you want
  365.            the program to continue,    you must remember to pop the
  366.            _u_n_d_e_f from the stack.
  367.  
  368.       See _U_s_i_n_g _G__E_V_A_L for details on using    G_EVAL.
  369.  
  370.       GGGG____KKKKEEEEEEEEPPPPEEEERRRRRRRR
  371.  
  372.       You may have noticed that using the G_EVAL flag described
  373.       above    will aaaallllwwwwaaaayyyyssss clear the $@ variable and set it to    a
  374.       string describing the    error iff there    was an error in    the
  375.       called code.    This unqualified resetting of $@ can be
  376.       problematic in the reliable identification of    errors using
  377.       the eval {} mechanism, because the possibility exists    that
  378.       perl will call other code (end of block processing code, for
  379.       example) between the time the    error causes $@    to be set
  380.       within eval {}, and the subsequent statement which checks
  381.       for the value    of $@ gets executed in the user's script.
  382.  
  383.       This scenario    will mostly be applicable to code that is
  384.       meant    to be called from within destructors, asynchronous
  385.       callbacks, signal handlers, __DIE__ or __WARN__ hooks, and
  386.       tie functions.  In such situations, you will not want    to
  387.       clear    $@ at all, but simply to append    any new    errors to any
  388.       existing value of $@.
  389.  
  390.  
  391.  
  392.  
  393.      Page 6                        (printed 10/23/98)
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  401.  
  402.  
  403.  
  404.       The G_KEEPERR    flag is    meant to be used in conjunction    with
  405.       G_EVAL in _p_e_r_l__c_a_l_l_*    functions that are used    to implement
  406.       such code.  This flag    has no effect when G_EVAL is not used.
  407.  
  408.       When G_KEEPERR is used, any errors in    the called code    will
  409.       be prefixed with the string "\_t(in cleanup)",    and appended
  410.       to the current value of $@.
  411.  
  412.       The G_KEEPERR    flag was introduced in Perl version 5.002.
  413.  
  414.       See _U_s_i_n_g _G__K_E_E_P_E_R_R for an example of    a situation that
  415.       warrants the use of this flag.
  416.  
  417.       DDDDeeeetttteeeerrrrmmmmiiiinnnniiiinnnngggg tttthhhheeee CCCCoooonnnntttteeeexxxxtttt
  418.  
  419.       As mentioned above, you can determine    the context of the
  420.       currently executing subroutine in Perl with _w_a_n_t_a_r_r_a_y.  The
  421.       equivalent test can be made in C by using the    GIMME_V    macro,
  422.       which    returns    G_ARRAY    if you have been called    in an array
  423.       context, G_SCALAR if in a scalar context, or G_VOID if in a
  424.       void context (i.e. the return    value will not be used).  An
  425.       older    version    of this    macro is called    GIMME; in a void
  426.       context it returns G_SCALAR instead of G_VOID.  An example
  427.       of using the GIMME_V macro is    shown in section _U_s_i_n_g
  428.       _G_I_M_M_E__V.
  429.  
  430.      KKKKNNNNOOOOWWWWNNNN PPPPRRRROOOOBBBBLLLLEEEEMMMMSSSS
  431.       This section outlines    all known problems that    exist in the
  432.       _p_e_r_l__c_a_l_l_* functions.
  433.  
  434.       1.   If you are intending to make use    of both    the G_EVAL and
  435.            G_SCALAR    flags in your code, use    a version of Perl
  436.            greater than 5.000.  There is a bug in version 5.000 of
  437.            Perl which means    that the combination of    these two
  438.            flags will not work as described    in the section _F_L_A_G
  439.            _V_A_L_U_E_S.
  440.  
  441.            Specifically, if    the two    flags are used when calling a
  442.            subroutine and that subroutine does not call _d_i_e, the
  443.            value returned by _p_e_r_l__c_a_l_l_* will be wrong.
  444.  
  445.       2.   In Perl 5.000 and 5.001 there is    a problem with using
  446.            _p_e_r_l__c_a_l_l_* if the Perl sub you are calling attempts to
  447.            trap a _d_i_e.
  448.  
  449.            The symptom of this problem is that the called Perl sub
  450.            will continue to    completion, but    whenever it attempts
  451.            to pass control back to the XSUB, the program will
  452.            immediately terminate.
  453.  
  454.            For example, say    you want to call this Perl sub
  455.  
  456.  
  457.  
  458.  
  459.      Page 7                        (printed 10/23/98)
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  467.  
  468.  
  469.  
  470.            sub fred
  471.            {
  472.                eval { die "Fatal Error"    ; }
  473.                print "Trapped error: $@\n"
  474.                if $@ ;
  475.            }
  476.  
  477.            via this    XSUB
  478.  
  479.            void
  480.            Call_fred()
  481.                CODE:
  482.                PUSHMARK(SP) ;
  483.                perl_call_pv("fred", G_DISCARD|G_NOARGS)    ;
  484.                fprintf(stderr, "back in    Call_fred\n") ;
  485.  
  486.            When Call_fred is executed it will print
  487.  
  488.            Trapped error: Fatal    Error
  489.  
  490.            As control never    returns    to Call_fred, the "back    in
  491.            Call_fred" string will not get printed.
  492.  
  493.            To work around this problem, you    can either upgrade to
  494.            Perl 5.002 or higher, or    use the    G_EVAL flag with
  495.            _p_e_r_l__c_a_l_l_* as shown below
  496.  
  497.            void
  498.            Call_fred()
  499.                CODE:
  500.                PUSHMARK(SP) ;
  501.                perl_call_pv("fred", G_EVAL|G_DISCARD|G_NOARGS) ;
  502.                fprintf(stderr, "back in    Call_fred\n") ;
  503.  
  504.  
  505.      EEEEXXXXAAAAMMMMPPPPLLLLEEEESSSS
  506.       Enough of the    definition talk, let's have a few examples.
  507.  
  508.       Perl provides    many macros to assist in accessing the Perl
  509.       stack.  Wherever possible, these macros should always    be
  510.       used when interfacing    to Perl    internals.  We hope this
  511.       should make the code less vulnerable to any changes made to
  512.       Perl in the future.
  513.  
  514.       Another point    worth noting is    that in    the first series of
  515.       examples I have made use of only the _p_e_r_l__c_a_l_l__p_v function.
  516.       This has been    done to    keep the code simpler and ease you
  517.       into the topic.  Wherever possible, if the choice is between
  518.       using    _p_e_r_l__c_a_l_l__p_v and _p_e_r_l__c_a_l_l__s_v, you should always try
  519.       to use _p_e_r_l__c_a_l_l__s_v.    See _U_s_i_n_g _p_e_r_l__c_a_l_l__s_v for details.
  520.  
  521.  
  522.  
  523.  
  524.  
  525.      Page 8                        (printed 10/23/98)
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  533.  
  534.  
  535.  
  536.       NNNNoooo PPPPaaaarrrraaaammmmeeeetttteeeerrrrssss,,,, NNNNooootttthhhhiiiinnnngggg rrrreeeettttuuuurrrrnnnneeeedddd
  537.  
  538.       This first trivial example will call a Perl subroutine,
  539.       _P_r_i_n_t_U_I_D, to print out the UID of the    process.
  540.  
  541.           sub PrintUID
  542.           {
  543.           print    "UID is    $<\n" ;
  544.           }
  545.  
  546.       and here is a    C function to call it
  547.  
  548.           static void
  549.           call_PrintUID()
  550.           {
  551.           dSP ;
  552.  
  553.           PUSHMARK(SP) ;
  554.           perl_call_pv("PrintUID", G_DISCARD|G_NOARGS) ;
  555.           }
  556.  
  557.       Simple, eh.
  558.  
  559.       A few    points to note about this example.
  560.  
  561.       1.   Ignore dSP and PUSHMARK(SP) for now. They will be
  562.            discussed in the    next example.
  563.  
  564.       2.   We aren't passing any parameters    to _P_r_i_n_t_U_I_D so
  565.            G_NOARGS    can be specified.
  566.  
  567.       3.   We aren't interested in anything    returned from
  568.            _P_r_i_n_t_U_I_D, so G_DISCARD is specified. Even if _P_r_i_n_t_U_I_D
  569.            was changed to return some _v_a_l_u_e(s), having specified
  570.            G_DISCARD will mean that    they will be wiped by the time
  571.            control returns from _p_e_r_l__c_a_l_l__p_v.
  572.  
  573.       4.   As _p_e_r_l__c_a_l_l__p_v is being    used, the Perl subroutine is
  574.            specified as a C    string.    In this    case the subroutine
  575.            name has    been 'hard-wired' into the code.
  576.  
  577.       5.   Because we specified G_DISCARD, it is not necessary to
  578.            check the value returned    from _p_e_r_l__c_a_l_l__p_v. It will
  579.            always be 0.
  580.  
  581.       PPPPaaaassssssssiiiinnnngggg PPPPaaaarrrraaaammmmeeeetttteeeerrrrssss
  582.  
  583.       Now let's make a slightly more complex example. This time we
  584.       want to call a Perl subroutine, LeftString, which will take
  585.       2 parameters - a string ($s) and an integer ($n).  The
  586.       subroutine will simply print the first $n characters of the
  587.       string.
  588.  
  589.  
  590.  
  591.      Page 9                        (printed 10/23/98)
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  599.  
  600.  
  601.  
  602.       So the Perl subroutine would look like this
  603.  
  604.           sub LeftString
  605.           {
  606.           my($s, $n) = @_ ;
  607.           print    substr($s, 0, $n), "\n"    ;
  608.           }
  609.  
  610.       The C    function required to call _L_e_f_t_S_t_r_i_n_g would look    like
  611.       this.
  612.  
  613.           static void
  614.           call_LeftString(a, b)
  615.           char * a ;
  616.           int b ;
  617.           {
  618.           dSP ;
  619.  
  620.           ENTER    ;
  621.           SAVETMPS ;
  622.  
  623.           PUSHMARK(SP) ;
  624.           XPUSHs(sv_2mortal(newSVpv(a, 0)));
  625.           XPUSHs(sv_2mortal(newSViv(b)));
  626.           PUTBACK ;
  627.  
  628.           perl_call_pv("LeftString", G_DISCARD);
  629.  
  630.           FREETMPS ;
  631.           LEAVE    ;
  632.           }
  633.  
  634.       Here are a few notes on the C    function _c_a_l_l__L_e_f_t_S_t_r_i_n_g.
  635.  
  636.       1.   Parameters are passed to    the Perl subroutine using the
  637.            Perl stack.  This is the    purpose    of the code beginning
  638.            with the    line dSP and ending with the line PUTBACK.
  639.            The dSP declares    a local    copy of    the stack pointer.
  640.            This local copy should aaaallllwwwwaaaayyyyssss be    accessed as SP.
  641.  
  642.       2.   If you are going    to put something onto the Perl stack,
  643.            you need    to know    where to put it. This is the purpose
  644.            of the macro dSP    - it declares and initializes a    _l_o_c_a_l
  645.            copy of the Perl    stack pointer.
  646.  
  647.            All the other macros which will be used in this example
  648.            require you to have used    this macro.
  649.  
  650.            The exception to    this rule is if    you are    calling    a Perl
  651.            subroutine directly from    an XSUB    function. In this case
  652.            it is not necessary to use the dSP macro    explicitly -
  653.            it will be declared for you automatically.
  654.  
  655.  
  656.  
  657.      Page 10                        (printed 10/23/98)
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  665.  
  666.  
  667.  
  668.       3.   Any parameters to be pushed onto    the stack should be
  669.            bracketed by the    PUSHMARK and PUTBACK macros.  The
  670.            purpose of these    two macros, in this context, is    to
  671.            count the number    of parameters you are pushing
  672.            automatically.  Then whenever Perl is creating the @_
  673.            array for the subroutine, it knows how big to make it.
  674.  
  675.            The PUSHMARK macro tells    Perl to    make a mental note of
  676.            the current stack pointer. Even if you aren't passing
  677.            any parameters (like the    example    shown in the section
  678.            _N_o _P_a_r_a_m_e_t_e_r_s, _N_o_t_h_i_n_g _r_e_t_u_r_n_e_d)    you must still call
  679.            the PUSHMARK macro before you can call any of the
  680.            _p_e_r_l__c_a_l_l_* functions - Perl still needs    to know    that
  681.            there are no parameters.
  682.  
  683.            The PUTBACK macro sets the global copy of the stack
  684.            pointer to be the same as our local copy. If we didn't
  685.            do this _p_e_r_l__c_a_l_l__p_v wouldn't know where    the two
  686.            parameters we pushed were - remember that up to now all
  687.            the stack pointer manipulation we have done is with our
  688.            local copy, _n_o_t the global copy.
  689.  
  690.       4.   The only    flag specified this time is G_DISCARD. Because
  691.            we are passing 2    parameters to the Perl subroutine this
  692.            time, we    have not specified G_NOARGS.
  693.  
  694.       5.   Next, we    come to    XPUSHs.    This is    where the parameters
  695.            actually    get pushed onto    the stack. In this case    we are
  696.            pushing a string    and an integer.
  697.  
  698.            See the section on _X_S_U_B_s    _a_n_d _t_h_e    _A_r_g_u_m_e_n_t _S_t_a_c_k in the
  699.            _p_e_r_l_g_u_t_s    manpage    for details on how the XPUSH macros
  700.            work.
  701.  
  702.       6.   Because we created temporary values (by means of
  703.            _s_v__2_m_o_r_t_a_l() calls) we will have    to tidy    up the Perl
  704.            stack and dispose of mortal SVs.
  705.  
  706.            This is the purpose of
  707.  
  708.            ENTER ;
  709.            SAVETMPS ;
  710.  
  711.            at the start of the function, and
  712.  
  713.            FREETMPS ;
  714.            LEAVE ;
  715.  
  716.            at the end. The ENTER/SAVETMPS pair creates a boundary
  717.            for any temporaries we create.  This means that the
  718.            temporaries we get rid of will be limited to those
  719.            which were created after    these calls.
  720.  
  721.  
  722.  
  723.      Page 11                        (printed 10/23/98)
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  731.  
  732.  
  733.  
  734.            The FREETMPS/LEAVE pair will get    rid of any values
  735.            returned    by the Perl subroutine (see next example),
  736.            plus it will also dump the mortal SVs we    have created.
  737.            Having ENTER/SAVETMPS at    the beginning of the code
  738.            makes sure that no other    mortals    are destroyed.
  739.  
  740.            Think of    these macros as    working    a bit like using { and
  741.            } in Perl to limit the scope of local variables.
  742.  
  743.            See the section _U_s_i_n_g _P_e_r_l _t_o _d_i_s_p_o_s_e _o_f    _t_e_m_p_o_r_a_r_i_e_s
  744.            for details of an alternative to    using these macros.
  745.  
  746.       7.   Finally,    _L_e_f_t_S_t_r_i_n_g can now be called via the
  747.            _p_e_r_l__c_a_l_l__p_v function.
  748.  
  749.       RRRReeeettttuuuurrrrnnnniiiinnnngggg aaaa SSSSccccaaaallllaaaarrrr
  750.  
  751.       Now for an example of    dealing    with the items returned    from a
  752.       Perl subroutine.
  753.  
  754.       Here is a Perl subroutine, _A_d_d_e_r, that takes 2 integer
  755.       parameters and simply    returns    their sum.
  756.  
  757.           sub Adder
  758.           {
  759.           my($a, $b) = @_ ;
  760.           $a + $b ;
  761.           }
  762.  
  763.       Because we are now concerned with the    return value from
  764.       _A_d_d_e_r, the C function    required to call it is now a bit more
  765.       complex.
  766.  
  767.           static void
  768.           call_Adder(a, b)
  769.           int a ;
  770.           int b ;
  771.           {
  772.           dSP ;
  773.           int count ;
  774.  
  775.           ENTER    ;
  776.           SAVETMPS;
  777.  
  778.           PUSHMARK(SP) ;
  779.           XPUSHs(sv_2mortal(newSViv(a)));
  780.           XPUSHs(sv_2mortal(newSViv(b)));
  781.           PUTBACK ;
  782.  
  783.           count    = perl_call_pv("Adder",    G_SCALAR);
  784.  
  785.           SPAGAIN ;
  786.  
  787.  
  788.  
  789.      Page 12                        (printed 10/23/98)
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  797.  
  798.  
  799.  
  800.           if (count != 1)
  801.               croak("Big trouble\n") ;
  802.  
  803.           printf ("The sum of %d and %d    is %d\n", a, b,    POPi) ;
  804.  
  805.           PUTBACK ;
  806.           FREETMPS ;
  807.           LEAVE    ;
  808.           }
  809.  
  810.       Points to note this time are
  811.  
  812.       1.   The only    flag specified this time was G_SCALAR. That
  813.            means the @_ array will be created and that the value
  814.            returned    by _A_d_d_e_r will still exist after    the call to
  815.            _p_e_r_l__c_a_l_l__p_v.
  816.  
  817.       2.   The purpose of the macro    SPAGAIN    is to refresh the
  818.            local copy of the stack pointer.    This is    necessary
  819.            because it is possible that the memory allocated    to the
  820.            Perl stack has been reallocated whilst in the
  821.            _p_e_r_l__c_a_l_l__p_v call.
  822.  
  823.            If you are making use of    the Perl stack pointer in your
  824.            code you    must always refresh the    local copy using
  825.            SPAGAIN whenever    you make use of    the _p_e_r_l__c_a_l_l_*
  826.            functions or any    other Perl internal function.
  827.  
  828.       3.   Although    only a single value was    expected to be
  829.            returned    from _A_d_d_e_r, it is still    good practice to check
  830.            the return code from _p_e_r_l__c_a_l_l__p_v anyway.
  831.  
  832.            Expecting a single value    is not quite the same as
  833.            knowing that there will be one. If someone modified
  834.            _A_d_d_e_r to    return a list and we didn't check for that
  835.            possibility and take appropriate    action the Perl    stack
  836.            would end up in an inconsistent state. That is
  837.            something you _r_e_a_l_l_y don't want to happen ever.
  838.  
  839.       4.   The POPi    macro is used here to pop the return value
  840.            from the    stack.    In this    case we    wanted an integer, so
  841.            POPi was    used.
  842.  
  843.            Here is the complete list of POP    macros available,
  844.            along with the types they return.
  845.  
  846.            POPs           SV
  847.            POPp           pointer
  848.            POPn           double
  849.            POPi           integer
  850.            POPl           long
  851.  
  852.  
  853.  
  854.  
  855.      Page 13                        (printed 10/23/98)
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  863.  
  864.  
  865.  
  866.       5.   The final PUTBACK is used to leave the Perl stack in a
  867.            consistent state    before exiting the function.  This is
  868.            necessary because when we popped    the return value from
  869.            the stack with POPi it updated only our local copy of
  870.            the stack pointer.  Remember, PUTBACK sets the global
  871.            stack pointer to    be the same as our local copy.
  872.  
  873.       RRRReeeettttuuuurrrrnnnniiiinnnngggg aaaa lllliiiisssstttt ooooffff vvvvaaaalllluuuueeeessss
  874.  
  875.       Now, let's extend the    previous example to return both    the
  876.       sum of the parameters    and the    difference.
  877.  
  878.       Here is the Perl subroutine
  879.  
  880.           sub AddSubtract
  881.           {
  882.          my($a,    $b) = @_ ;
  883.          ($a+$b, $a-$b)    ;
  884.           }
  885.  
  886.       and this is the C function
  887.  
  888.           static void
  889.           call_AddSubtract(a, b)
  890.           int a ;
  891.           int b ;
  892.           {
  893.           dSP ;
  894.           int count ;
  895.  
  896.           ENTER    ;
  897.           SAVETMPS;
  898.  
  899.           PUSHMARK(SP) ;
  900.           XPUSHs(sv_2mortal(newSViv(a)));
  901.           XPUSHs(sv_2mortal(newSViv(b)));
  902.           PUTBACK ;
  903.  
  904.           count    = perl_call_pv("AddSubtract", G_ARRAY);
  905.  
  906.           SPAGAIN ;
  907.  
  908.           if (count != 2)
  909.               croak("Big trouble\n") ;
  910.  
  911.           printf ("%d -    %d = %d\n", a, b, POPi)    ;
  912.           printf ("%d +    %d = %d\n", a, b, POPi)    ;
  913.  
  914.           PUTBACK ;
  915.           FREETMPS ;
  916.           LEAVE    ;
  917.           }
  918.  
  919.  
  920.  
  921.      Page 14                        (printed 10/23/98)
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  929.  
  930.  
  931.  
  932.       If _c_a_l_l__A_d_d_S_u_b_t_r_a_c_t is called    like this
  933.  
  934.           call_AddSubtract(7, 4) ;
  935.  
  936.       then here is the output
  937.  
  938.           7    - 4 = 3
  939.           7    + 4 = 11
  940.  
  941.       Notes
  942.  
  943.       1.   We wanted array context,    so G_ARRAY was used.
  944.  
  945.       2.   Not surprisingly    POPi is    used twice this    time because
  946.            we were retrieving 2 values from    the stack. The
  947.            important thing to note is that when using the POP*
  948.            macros they come    off the    stack in _r_e_v_e_r_s_e order.
  949.  
  950.       RRRReeeettttuuuurrrrnnnniiiinnnngggg aaaa lllliiiisssstttt iiiinnnn aaaa    ssssccccaaaallllaaaarrrr ccccoooonnnntttteeeexxxxtttt
  951.  
  952.       Say the Perl subroutine in the previous section was called
  953.       in a scalar context, like this
  954.  
  955.           static void
  956.           call_AddSubScalar(a, b)
  957.           int a ;
  958.           int b ;
  959.           {
  960.           dSP ;
  961.           int count ;
  962.           int i    ;
  963.  
  964.           ENTER    ;
  965.           SAVETMPS;
  966.  
  967.           PUSHMARK(SP) ;
  968.           XPUSHs(sv_2mortal(newSViv(a)));
  969.           XPUSHs(sv_2mortal(newSViv(b)));
  970.           PUTBACK ;
  971.  
  972.           count    = perl_call_pv("AddSubtract", G_SCALAR);
  973.  
  974.           SPAGAIN ;
  975.  
  976.           printf ("Items Returned = %d\n", count) ;
  977.  
  978.           for (i = 1 ; i <= count ; ++i)
  979.               printf ("Value %d    = %d\n", i, POPi) ;
  980.  
  981.  
  982.  
  983.  
  984.  
  985.  
  986.  
  987.      Page 15                        (printed 10/23/98)
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  995.  
  996.  
  997.  
  998.           PUTBACK ;
  999.           FREETMPS ;
  1000.           LEAVE    ;
  1001.           }
  1002.  
  1003.       The other modification made is that _c_a_l_l__A_d_d_S_u_b_S_c_a_l_a_r    will
  1004.       print    the number of items returned from the Perl subroutine
  1005.       and their value (for simplicity it assumes that they are
  1006.       integer).  So    if _c_a_l_l__A_d_d_S_u_b_S_c_a_l_a_r is    called
  1007.  
  1008.           call_AddSubScalar(7, 4) ;
  1009.  
  1010.       then the output will be
  1011.  
  1012.           Items Returned = 1
  1013.           Value 1 =    3
  1014.  
  1015.       In this case the main    point to note is that only the last
  1016.       item in the list is returned from the    subroutine,
  1017.       _A_d_d_S_u_b_t_r_a_c_t actually made it back to _c_a_l_l__A_d_d_S_u_b_S_c_a_l_a_r.
  1018.  
  1019.       RRRReeeettttuuuurrrrnnnniiiinnnngggg DDDDaaaattttaaaa ffffrrrroooommmm PPPPeeeerrrrllll vvvviiiiaaaa tttthhhheeee ppppaaaarrrraaaammmmeeeetttteeeerrrr lllliiiisssstttt
  1020.  
  1021.       It is    also possible to return    values directly    via the
  1022.       parameter list - whether it is actually desirable to do it
  1023.       is another matter entirely.
  1024.  
  1025.       The Perl subroutine, _I_n_c, below takes    2 parameters and
  1026.       increments each directly.
  1027.  
  1028.           sub Inc
  1029.           {
  1030.           ++ $_[0] ;
  1031.           ++ $_[1] ;
  1032.           }
  1033.  
  1034.       and here is a    C function to call it.
  1035.  
  1036.           static void
  1037.           call_Inc(a, b)
  1038.           int a ;
  1039.           int b ;
  1040.           {
  1041.           dSP ;
  1042.           int count ;
  1043.           SV * sva ;
  1044.           SV * svb ;
  1045.  
  1046.           ENTER    ;
  1047.           SAVETMPS;
  1048.  
  1049.  
  1050.  
  1051.  
  1052.  
  1053.      Page 16                        (printed 10/23/98)
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1061.  
  1062.  
  1063.  
  1064.           sva =    sv_2mortal(newSViv(a)) ;
  1065.           svb =    sv_2mortal(newSViv(b)) ;
  1066.  
  1067.           PUSHMARK(SP) ;
  1068.           XPUSHs(sva);
  1069.           XPUSHs(svb);
  1070.           PUTBACK ;
  1071.  
  1072.           count    = perl_call_pv("Inc", G_DISCARD);
  1073.  
  1074.           if (count != 0)
  1075.               croak ("call_Inc:    expected 0 values from 'Inc', got %d\n",
  1076.                  count) ;
  1077.  
  1078.           printf ("%d +    1 = %d\n", a, SvIV(sva)) ;
  1079.           printf ("%d +    1 = %d\n", b, SvIV(svb)) ;
  1080.  
  1081.           FREETMPS ;
  1082.           LEAVE    ;
  1083.           }
  1084.  
  1085.       To be    able to    access the two parameters that were pushed
  1086.       onto the stack after they return from    _p_e_r_l__c_a_l_l__p_v it    is
  1087.       necessary to make a note of their addresses -    thus the two
  1088.       variables sva    and svb.
  1089.  
  1090.       The reason this is necessary is that the area    of the Perl
  1091.       stack    which held them    will very likely have been overwritten
  1092.       by something else by the time    control    returns    from
  1093.       _p_e_r_l__c_a_l_l__p_v.
  1094.  
  1095.       UUUUssssiiiinnnngggg    GGGG____EEEEVVVVAAAALLLL
  1096.  
  1097.       Now an example using G_EVAL. Below is    a Perl subroutine
  1098.       which    computes the difference    of its 2 parameters. If    this
  1099.       would    result in a negative result, the subroutine calls _d_i_e.
  1100.  
  1101.           sub Subtract
  1102.           {
  1103.           my ($a, $b) =    @_ ;
  1104.  
  1105.           die "death can be fatal\n" if    $a < $b    ;
  1106.  
  1107.           $a - $b ;
  1108.           }
  1109.  
  1110.       and some C to    call it
  1111.  
  1112.  
  1113.  
  1114.  
  1115.  
  1116.  
  1117.  
  1118.  
  1119.      Page 17                        (printed 10/23/98)
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1127.  
  1128.  
  1129.  
  1130.           static void
  1131.           call_Subtract(a, b)
  1132.           int a ;
  1133.           int b ;
  1134.           {
  1135.           dSP ;
  1136.           int count ;
  1137.  
  1138.           ENTER    ;
  1139.           SAVETMPS;
  1140.  
  1141.           PUSHMARK(SP) ;
  1142.           XPUSHs(sv_2mortal(newSViv(a)));
  1143.           XPUSHs(sv_2mortal(newSViv(b)));
  1144.           PUTBACK ;
  1145.  
  1146.           count    = perl_call_pv("Subtract", G_EVAL|G_SCALAR);
  1147.  
  1148.           SPAGAIN ;
  1149.  
  1150.           /* Check the eval first */
  1151.           if (SvTRUE(ERRSV))
  1152.           {
  1153.               printf ("Uh oh - %s\n", SvPV(ERRSV, PL_na)) ;
  1154.               POPs ;
  1155.           }
  1156.           else
  1157.           {
  1158.               if (count    != 1)
  1159.              croak("call_Subtract: wanted 1    value from 'Subtract', got %d\n",
  1160.                   count) ;
  1161.  
  1162.               printf ("%d - %d = %d\n",    a, b, POPi) ;
  1163.           }
  1164.  
  1165.           PUTBACK ;
  1166.           FREETMPS ;
  1167.           LEAVE    ;
  1168.           }
  1169.  
  1170.       If _c_a_l_l__S_u_b_t_r_a_c_t is called thus
  1171.  
  1172.           call_Subtract(4, 5)
  1173.  
  1174.       the following    will be    printed
  1175.  
  1176.           Uh oh - death can    be fatal
  1177.  
  1178.       Notes
  1179.  
  1180.       1.   We want to be able to catch the _d_i_e so we have used the
  1181.            G_EVAL flag.  Not specifying this flag would mean that
  1182.  
  1183.  
  1184.  
  1185.      Page 18                        (printed 10/23/98)
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1193.  
  1194.  
  1195.  
  1196.            the program would terminate immediately at the _d_i_e
  1197.            statement in the    subroutine _S_u_b_t_r_a_c_t.
  1198.  
  1199.       2.   The code
  1200.  
  1201.            if (SvTRUE(ERRSV))
  1202.            {
  1203.                printf ("Uh oh -    %s\n", SvPV(ERRSV, PL_na)) ;
  1204.                POPs ;
  1205.            }
  1206.  
  1207.            is the direct equivalent    of this    bit of Perl
  1208.  
  1209.            print "Uh oh    - $@\n"    if $@ ;
  1210.  
  1211.            PL_errgv    is a perl global of type GV * that points to
  1212.            the symbol table    entry containing the error.  ERRSV
  1213.            therefore refers    to the C equivalent of $@.
  1214.  
  1215.       3.   Note that the stack is popped using POPs    in the block
  1216.            where SvTRUE(ERRSV) is true.  This is necessary because
  1217.            whenever    a _p_e_r_l__c_a_l_l_* function invoked with
  1218.            G_EVAL|G_SCALAR returns an error, the top of the    stack
  1219.            holds the value _u_n_d_e_f. Because we want the program to
  1220.            continue    after detecting    this error, it is essential
  1221.            that the    stack is tidied    up by removing the _u_n_d_e_f.
  1222.  
  1223.       UUUUssssiiiinnnngggg    GGGG____KKKKEEEEEEEEPPPPEEEERRRRRRRR
  1224.  
  1225.       Consider this    rather facetious example, where    we have    used
  1226.       an XS    version    of the call_Subtract example above inside a
  1227.       destructor:
  1228.  
  1229.           package Foo;
  1230.           sub new {    bless {}, $_[0]    }
  1231.           sub Subtract {
  1232.           my($a,$b) = @_;
  1233.           die "death can be fatal" if $a < $b ;
  1234.           $a - $b;
  1235.           }
  1236.           sub DESTROY { call_Subtract(5, 4); }
  1237.           sub foo {    die "foo dies";    }
  1238.  
  1239.           package main;
  1240.           eval { Foo->new->foo };
  1241.           print "Saw: $@" if $@;         # should be, but isn't
  1242.  
  1243.       This example will fail to recognize that an error occurred
  1244.       inside the eval {}.  Here's why: the call_Subtract code got
  1245.       executed while perl was cleaning up temporaries when exiting
  1246.       the eval block, and because call_Subtract is implemented
  1247.       with _p_e_r_l__c_a_l_l__p_v using the G_EVAL flag, it promptly reset
  1248.  
  1249.  
  1250.  
  1251.      Page 19                        (printed 10/23/98)
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1259.  
  1260.  
  1261.  
  1262.       $@.  This results in the failure of the outermost test for
  1263.       $@, and thereby the failure of the error trap.
  1264.  
  1265.       Appending the    G_KEEPERR flag,    so that    the _p_e_r_l__c_a_l_l__p_v call
  1266.       in call_Subtract reads:
  1267.  
  1268.           count    = perl_call_pv("Subtract", G_EVAL|G_SCALAR|G_KEEPERR);
  1269.  
  1270.       will preserve    the error and restore reliable error handling.
  1271.  
  1272.       UUUUssssiiiinnnngggg    ppppeeeerrrrllll____ccccaaaallllllll____ssssvvvv
  1273.  
  1274.       In all the previous examples I have 'hard-wired' the name of
  1275.       the Perl subroutine to be called from    C.  Most of the    time
  1276.       though, it is    more convenient    to be able to specify the name
  1277.       of the Perl subroutine from within the Perl script.
  1278.  
  1279.       Consider the Perl code below
  1280.  
  1281.           sub fred
  1282.           {
  1283.           print    "Hello there\n"    ;
  1284.           }
  1285.  
  1286.           CallSubPV("fred")    ;
  1287.  
  1288.       Here is a snippet of XSUB which defines _C_a_l_l_S_u_b_P_V.
  1289.  
  1290.           void
  1291.           CallSubPV(name)
  1292.           char *  name
  1293.           CODE:
  1294.           PUSHMARK(SP) ;
  1295.           perl_call_pv(name, G_DISCARD|G_NOARGS) ;
  1296.  
  1297.       That is fine as far as it goes. The thing is,    the Perl
  1298.       subroutine can be specified as only a    string.     For Perl 4
  1299.       this was adequate, but Perl 5    allows references to
  1300.       subroutines and anonymous subroutines.  This is where
  1301.       _p_e_r_l__c_a_l_l__s_v is useful.
  1302.  
  1303.       The code below for _C_a_l_l_S_u_b_S_V is identical to _C_a_l_l_S_u_b_P_V
  1304.       except that the name parameter is now    defined    as an SV* and
  1305.       we use _p_e_r_l__c_a_l_l__s_v instead of _p_e_r_l__c_a_l_l__p_v.
  1306.  
  1307.           void
  1308.           CallSubSV(name)
  1309.           SV *      name
  1310.           CODE:
  1311.           PUSHMARK(SP) ;
  1312.           perl_call_sv(name, G_DISCARD|G_NOARGS) ;
  1313.  
  1314.  
  1315.  
  1316.  
  1317.      Page 20                        (printed 10/23/98)
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1325.  
  1326.  
  1327.  
  1328.       Because we are using an SV to    call _f_r_e_d the following    can
  1329.       all be used
  1330.  
  1331.           CallSubSV("fred")    ;
  1332.           CallSubSV(\&fred)    ;
  1333.           $ref = \&fred ;
  1334.           CallSubSV($ref) ;
  1335.           CallSubSV( sub { print "Hello there\n" } ) ;
  1336.  
  1337.       As you can see, _p_e_r_l__c_a_l_l__s_v gives you much greater
  1338.       flexibility in how you can specify the Perl subroutine.
  1339.  
  1340.       You should note that if it is    necessary to store the SV
  1341.       (name    in the example above) which corresponds    to the Perl
  1342.       subroutine so    that it    can be used later in the program, it
  1343.       not enough just to store a copy of the pointer to the    SV.
  1344.       Say the code above had been like this
  1345.  
  1346.           static SV    * rememberSub ;
  1347.  
  1348.           void
  1349.           SaveSub1(name)
  1350.           SV *      name
  1351.           CODE:
  1352.           rememberSub =    name ;
  1353.  
  1354.           void
  1355.           CallSavedSub1()
  1356.           CODE:
  1357.           PUSHMARK(SP) ;
  1358.           perl_call_sv(rememberSub, G_DISCARD|G_NOARGS)    ;
  1359.  
  1360.       The reason this is wrong is that by the time you come    to use
  1361.       the pointer rememberSub in CallSavedSub1, it may or may not
  1362.       still    refer to the Perl subroutine that was recorded in
  1363.       SaveSub1.  This is particularly true for these cases
  1364.  
  1365.           SaveSub1(\&fred) ;
  1366.           CallSavedSub1() ;
  1367.  
  1368.           SaveSub1(    sub { print "Hello there\n" } )    ;
  1369.           CallSavedSub1() ;
  1370.  
  1371.       By the time each of the SaveSub1 statements above have been
  1372.       executed, the    SV*s which corresponded    to the parameters will
  1373.       no longer exist.  Expect an error message from Perl of the
  1374.       form
  1375.  
  1376.           Can't use    an undefined value as a    subroutine reference at    ...
  1377.  
  1378.       for each of the CallSavedSub1    lines.
  1379.  
  1380.  
  1381.  
  1382.  
  1383.      Page 21                        (printed 10/23/98)
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1391.  
  1392.  
  1393.  
  1394.       Similarly, with this code
  1395.  
  1396.           $ref = \&fred ;
  1397.           SaveSub1($ref) ;
  1398.           $ref = 47    ;
  1399.           CallSavedSub1() ;
  1400.  
  1401.       you can expect one of    these messages (which you actually get
  1402.       is dependent on the version of Perl you are using)
  1403.  
  1404.           Not a CODE reference at ...
  1405.           Undefined    subroutine &main::47 called ...
  1406.  
  1407.       The variable $ref may    have referred to the subroutine    fred
  1408.       whenever the call to SaveSub1    was made but by    the time
  1409.       CallSavedSub1    gets called it now holds the number 47.
  1410.       Because we saved only    a pointer to the original SV in
  1411.       SaveSub1, any    changes    to $ref    will be    tracked    by the pointer
  1412.       rememberSub. This means that whenever    CallSavedSub1 gets
  1413.       called, it will attempt to execute the code which is
  1414.       referenced by    the SV*    rememberSub.  In this case though, it
  1415.       now refers to    the integer 47,    so expect Perl to complain
  1416.       loudly.
  1417.  
  1418.       A similar but    more subtle problem is illustrated with    this
  1419.       code
  1420.  
  1421.           $ref = \&fred ;
  1422.           SaveSub1($ref) ;
  1423.           $ref = \&joe ;
  1424.           CallSavedSub1() ;
  1425.  
  1426.       This time whenever CallSavedSub1 get called it will execute
  1427.       the Perl subroutine joe (assuming it exists) rather than
  1428.       fred as was originally requested in the call to SaveSub1.
  1429.  
  1430.       To get around    these problems it is necessary to take a full
  1431.       copy of the SV.  The code below shows    SaveSub2 modified to
  1432.       do that
  1433.  
  1434.           static SV    * keepSub = (SV*)NULL ;
  1435.  
  1436.  
  1437.  
  1438.  
  1439.  
  1440.  
  1441.  
  1442.  
  1443.  
  1444.  
  1445.  
  1446.  
  1447.  
  1448.  
  1449.      Page 22                        (printed 10/23/98)
  1450.  
  1451.  
  1452.  
  1453.  
  1454.  
  1455.  
  1456.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1457.  
  1458.  
  1459.  
  1460.           void
  1461.           SaveSub2(name)
  1462.           SV *      name
  1463.           CODE:
  1464.           /* Take a copy of the    callback */
  1465.           if (keepSub == (SV*)NULL)
  1466.               /* First time, so    create a new SV    */
  1467.               keepSub =    newSVsv(name) ;
  1468.           else
  1469.               /* Been here before, so overwrite    */
  1470.               SvSetSV(keepSub, name) ;
  1471.  
  1472.           void
  1473.           CallSavedSub2()
  1474.           CODE:
  1475.           PUSHMARK(SP) ;
  1476.           perl_call_sv(keepSub,    G_DISCARD|G_NOARGS) ;
  1477.  
  1478.       To avoid creating a new SV every time    SaveSub2 is called,
  1479.       the function first checks to see if it has been called
  1480.       before.  If not, then    space for a new    SV is allocated    and
  1481.       the reference    to the Perl subroutine,    name is    copied to the
  1482.       variable keepSub in one operation using newSVsv.
  1483.       Thereafter, whenever SaveSub2    is called the existing SV,
  1484.       keepSub, is overwritten with the new value using SvSetSV.
  1485.  
  1486.       UUUUssssiiiinnnngggg    ppppeeeerrrrllll____ccccaaaallllllll____aaaarrrrggggvvvv
  1487.  
  1488.       Here is a Perl subroutine which prints whatever parameters
  1489.       are passed to    it.
  1490.  
  1491.           sub PrintList
  1492.           {
  1493.           my(@list) = @_ ;
  1494.  
  1495.           foreach (@list) { print "$_\n" }
  1496.           }
  1497.  
  1498.       and here is an example of _p_e_r_l__c_a_l_l__a_r_g_v which will call
  1499.       _P_r_i_n_t_L_i_s_t.
  1500.  
  1501.           static char * words[] = {"alpha",    "beta",    "gamma", "delta", NULL}    ;
  1502.  
  1503.           static void
  1504.           call_PrintList()
  1505.           {
  1506.           dSP ;
  1507.  
  1508.           perl_call_argv("PrintList", G_DISCARD, words)    ;
  1509.           }
  1510.  
  1511.       Note that it is not necessary    to call    PUSHMARK in this
  1512.  
  1513.  
  1514.  
  1515.      Page 23                        (printed 10/23/98)
  1516.  
  1517.  
  1518.  
  1519.  
  1520.  
  1521.  
  1522.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1523.  
  1524.  
  1525.  
  1526.       instance.  This is because _p_e_r_l__c_a_l_l__a_r_g_v will do it for
  1527.       you.
  1528.  
  1529.       UUUUssssiiiinnnngggg    ppppeeeerrrrllll____ccccaaaallllllll____mmmmeeeetttthhhhoooodddd
  1530.  
  1531.       Consider the following Perl code
  1532.  
  1533.           {
  1534.           package Mine ;
  1535.  
  1536.           sub new
  1537.           {
  1538.               my($type)    = shift    ;
  1539.               bless [@_]
  1540.           }
  1541.  
  1542.           sub Display
  1543.           {
  1544.               my ($self, $index) = @_ ;
  1545.               print "$index: $$self[$index]\n" ;
  1546.           }
  1547.  
  1548.           sub PrintID
  1549.           {
  1550.               my($class) = @_ ;
  1551.               print "This is Class $class version 1.0\n" ;
  1552.           }
  1553.           }
  1554.  
  1555.       It implements    just a very simple class to manage an array.
  1556.       Apart    from the constructor, new, it declares methods,    one
  1557.       static and one virtual. The static method, PrintID, prints
  1558.       out simply the class name and    a version number. The virtual
  1559.       method, Display, prints out a    single element of the array.
  1560.       Here is an all Perl example of using it.
  1561.  
  1562.           $a = new Mine ('red', 'green', 'blue') ;
  1563.           $a->Display(1) ;
  1564.           PrintID Mine;
  1565.  
  1566.       will print
  1567.  
  1568.           1: green
  1569.           This is Class Mine version 1.0
  1570.  
  1571.       Calling a Perl method    from C is fairly straightforward. The
  1572.       following things are required
  1573.  
  1574.       +o    a reference to the object for a virtual method or the
  1575.            name of the class for a static method.
  1576.  
  1577.  
  1578.  
  1579.  
  1580.  
  1581.      Page 24                        (printed 10/23/98)
  1582.  
  1583.  
  1584.  
  1585.  
  1586.  
  1587.  
  1588.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1589.  
  1590.  
  1591.  
  1592.       +o    the name    of the method.
  1593.  
  1594.       +o    any other parameters specific to    the method.
  1595.  
  1596.       Here is a simple XSUB    which illustrates the mechanics    of
  1597.       calling both the PrintID and Display methods from C.
  1598.  
  1599.           void
  1600.           call_Method(ref, method, index)
  1601.           SV *      ref
  1602.           char *  method
  1603.           int          index
  1604.           CODE:
  1605.           PUSHMARK(SP);
  1606.           XPUSHs(ref);
  1607.           XPUSHs(sv_2mortal(newSViv(index))) ;
  1608.           PUTBACK;
  1609.  
  1610.           perl_call_method(method, G_DISCARD) ;
  1611.  
  1612.           void
  1613.           call_PrintID(class, method)
  1614.           char *  class
  1615.           char *  method
  1616.           CODE:
  1617.           PUSHMARK(SP);
  1618.           XPUSHs(sv_2mortal(newSVpv(class, 0)))    ;
  1619.           PUTBACK;
  1620.  
  1621.           perl_call_method(method, G_DISCARD) ;
  1622.  
  1623.       So the methods PrintID and Display can be invoked like this
  1624.  
  1625.           $a = new Mine ('red', 'green', 'blue') ;
  1626.           call_Method($a, 'Display', 1) ;
  1627.           call_PrintID('Mine', 'PrintID') ;
  1628.  
  1629.       The only thing to note is that in both the static and
  1630.       virtual methods, the method name is not passed via the stack
  1631.       - it is used as the first parameter to _p_e_r_l__c_a_l_l__m_e_t_h_o_d.
  1632.  
  1633.       UUUUssssiiiinnnngggg    GGGGIIIIMMMMMMMMEEEE____VVVV
  1634.  
  1635.       Here is a trivial XSUB which prints the context in which it
  1636.       is currently executing.
  1637.  
  1638.  
  1639.  
  1640.  
  1641.  
  1642.  
  1643.  
  1644.  
  1645.  
  1646.  
  1647.      Page 25                        (printed 10/23/98)
  1648.  
  1649.  
  1650.  
  1651.  
  1652.  
  1653.  
  1654.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1655.  
  1656.  
  1657.  
  1658.           void
  1659.           PrintContext()
  1660.           CODE:
  1661.           I32 gimme = GIMME_V;
  1662.           if (gimme == G_VOID)
  1663.               printf ("Context is Void\n") ;
  1664.           else if (gimme == G_SCALAR)
  1665.               printf ("Context is Scalar\n") ;
  1666.           else
  1667.               printf ("Context is Array\n") ;
  1668.  
  1669.       and here is some Perl    to test    it
  1670.  
  1671.           PrintContext ;
  1672.           $a = PrintContext    ;
  1673.           @a = PrintContext    ;
  1674.  
  1675.       The output from that will be
  1676.  
  1677.           Context is Void
  1678.           Context is Scalar
  1679.           Context is Array
  1680.  
  1681.  
  1682.       UUUUssssiiiinnnngggg    PPPPeeeerrrrllll ttttoooo    ddddiiiissssppppoooosssseeee    ooooffff tttteeeemmmmppppoooorrrraaaarrrriiiieeeessss
  1683.  
  1684.       In the examples given    to date, any temporaries created in
  1685.       the callback (i.e., parameters passed    on the stack to    the
  1686.       _p_e_r_l__c_a_l_l_* function or values returned via the stack) have
  1687.       been freed by    one of these methods
  1688.  
  1689.       +o    specifying the G_DISCARD    flag with _p_e_r_l__c_a_l_l_*.
  1690.  
  1691.       +o    explicitly disposed of using the    ENTER/SAVETMPS -
  1692.            FREETMPS/LEAVE pairing.
  1693.  
  1694.       There    is another method which    can be used, namely letting
  1695.       Perl do it for you automatically whenever it regains control
  1696.       after    the callback has terminated.  This is done by simply
  1697.       not using the
  1698.  
  1699.           ENTER ;
  1700.           SAVETMPS ;
  1701.           ...
  1702.           FREETMPS ;
  1703.           LEAVE ;
  1704.  
  1705.       sequence in the callback (and    not, of    course,    specifying the
  1706.       G_DISCARD flag).
  1707.  
  1708.       If you are going to use this method you have to be aware of
  1709.       a possible memory leak which can arise under very specific
  1710.  
  1711.  
  1712.  
  1713.      Page 26                        (printed 10/23/98)
  1714.  
  1715.  
  1716.  
  1717.  
  1718.  
  1719.  
  1720.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1721.  
  1722.  
  1723.  
  1724.       circumstances.  To explain these circumstances you need to
  1725.       know a bit about the flow of control between Perl and    the
  1726.       callback routine.
  1727.  
  1728.       The examples given at    the start of the document (an error
  1729.       handler and an event driven program) are typical of the two
  1730.       main sorts of    flow control that you are likely to encounter
  1731.       with callbacks.  There is a very important distinction
  1732.       between them,    so pay attention.
  1733.  
  1734.       In the first example,    an error handler, the flow of control
  1735.       could    be as follows.    You have created an interface to an
  1736.       external library.  Control can reach the external library
  1737.       like this
  1738.  
  1739.           perl --> XSUB -->    external library
  1740.  
  1741.       Whilst control is in the library, an error condition occurs.
  1742.       You have previously set up a Perl callback to    handle this
  1743.       situation, so    it will    get executed. Once the callback    has
  1744.       finished, control will drop back to Perl again.  Here    is
  1745.       what the flow    of control will    be like    in that    situation
  1746.  
  1747.           perl --> XSUB -->    external library
  1748.                 ...
  1749.                 error occurs
  1750.                 ...
  1751.                 external library --> perl_call --> perl
  1752.                                     |
  1753.           perl <-- XSUB <--    external library <-- perl_call <----+
  1754.  
  1755.       After    processing of the error    using _p_e_r_l__c_a_l_l_* is
  1756.       completed, control reverts back to Perl more or less
  1757.       immediately.
  1758.  
  1759.       In the diagram, the further right you    go the more deeply
  1760.       nested the scope is.    It is only when    control    is back    with
  1761.       perl on the extreme left of the diagram that you will    have
  1762.       dropped back to the enclosing    scope and any temporaries you
  1763.       have left hanging around will    be freed.
  1764.  
  1765.       In the second    example, an event driven program, the flow of
  1766.       control will be more like this
  1767.  
  1768.  
  1769.  
  1770.  
  1771.  
  1772.  
  1773.  
  1774.  
  1775.  
  1776.  
  1777.  
  1778.  
  1779.      Page 27                        (printed 10/23/98)
  1780.  
  1781.  
  1782.  
  1783.  
  1784.  
  1785.  
  1786.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1787.  
  1788.  
  1789.  
  1790.           perl --> XSUB -->    event handler
  1791.                 ...
  1792.                 event handler --> perl_call -->    perl
  1793.                                  |
  1794.                 event handler <-- perl_call <----+
  1795.                 ...
  1796.                 event handler --> perl_call -->    perl
  1797.                                  |
  1798.                 event handler <-- perl_call <----+
  1799.                 ...
  1800.                 event handler --> perl_call -->    perl
  1801.                                  |
  1802.                 event handler <-- perl_call <----+
  1803.  
  1804.       In this case the flow    of control can consist of only the
  1805.       repeated sequence
  1806.  
  1807.           event handler -->    perl_call --> perl
  1808.  
  1809.       for practically the complete duration    of the program.     This
  1810.       means    that control may _n_e_v_e_r drop back to the    surrounding
  1811.       scope    in Perl    at the extreme left.
  1812.  
  1813.       So what is the big problem? Well, if you are expecting Perl
  1814.       to tidy up those temporaries for you,    you might be in    for a
  1815.       long wait.  For Perl to dispose of your temporaries, control
  1816.       must drop back to the    enclosing scope    at some    stage.    In the
  1817.       event    driven scenario    that may never happen.    This means
  1818.       that as time goes on,    your program will create more and more
  1819.       temporaries, none of which will ever be freed. As each of
  1820.       these    temporaries consumes some memory your program will
  1821.       eventually consume all the available memory in your system -
  1822.       kapow!
  1823.  
  1824.       So here is the bottom    line - if you are sure that control
  1825.       will revert back to the enclosing Perl scope fairly quickly
  1826.       after    the end    of your    callback, then it isn't    absolutely
  1827.       necessary to dispose explicitly of any temporaries you may
  1828.       have created.    Mind you, if you are at    all uncertain about
  1829.       what to do, it doesn't do any    harm to    tidy up    anyway.
  1830.  
  1831.       SSSSttttrrrraaaatttteeeeggggiiiieeeessss ffffoooorrrr ssssttttoooorrrriiiinnnngggg CCCCaaaallllllllbbbbaaaacccckkkk CCCCoooonnnntttteeeexxxxtttt IIIInnnnffffoooorrrrmmmmaaaattttiiiioooonnnn
  1832.  
  1833.       Potentially one of the trickiest problems to overcome    when
  1834.       designing a callback interface can be    figuring out how to
  1835.       store    the mapping between the    C callback function and    the
  1836.       Perl equivalent.
  1837.  
  1838.       To help understand why this can be a real problem first
  1839.       consider how a callback is set up in an all C    environment.
  1840.       Typically a C    API will provide a function to register    a
  1841.       callback.  This will expect a    pointer    to a function as one
  1842.  
  1843.  
  1844.  
  1845.      Page 28                        (printed 10/23/98)
  1846.  
  1847.  
  1848.  
  1849.  
  1850.  
  1851.  
  1852.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1853.  
  1854.  
  1855.  
  1856.       of its parameters.  Below is a call to a hypothetical
  1857.       function register_fatal which    registers the C    function to
  1858.       get called when a fatal error    occurs.
  1859.  
  1860.           register_fatal(cb1) ;
  1861.  
  1862.       The single parameter cb1 is a    pointer    to a function, so you
  1863.       must have defined cb1    in your    code, say something like this
  1864.  
  1865.           static void
  1866.           cb1()
  1867.           {
  1868.           printf ("Fatal Error\n") ;
  1869.           exit(1) ;
  1870.           }
  1871.  
  1872.       Now change that to call a Perl subroutine instead
  1873.  
  1874.           static SV    * callback = (SV*)NULL;
  1875.  
  1876.           static void
  1877.           cb1()
  1878.           {
  1879.           dSP ;
  1880.  
  1881.           PUSHMARK(SP) ;
  1882.  
  1883.           /* Call the Perl sub to process the callback */
  1884.           perl_call_sv(callback, G_DISCARD) ;
  1885.           }
  1886.  
  1887.           void
  1888.           register_fatal(fn)
  1889.           SV *      fn
  1890.           CODE:
  1891.           /* Remember the Perl sub */
  1892.           if (callback == (SV*)NULL)
  1893.               callback = newSVsv(fn) ;
  1894.           else
  1895.               SvSetSV(callback,    fn) ;
  1896.  
  1897.           /* register the callback with    the external library */
  1898.           register_fatal(cb1) ;
  1899.  
  1900.       where    the Perl equivalent of register_fatal and the callback
  1901.       it registers,    pcb1, might look like this
  1902.  
  1903.           #    Register the sub pcb1
  1904.           register_fatal(\&pcb1) ;
  1905.  
  1906.  
  1907.  
  1908.  
  1909.  
  1910.  
  1911.      Page 29                        (printed 10/23/98)
  1912.  
  1913.  
  1914.  
  1915.  
  1916.  
  1917.  
  1918.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1919.  
  1920.  
  1921.  
  1922.           sub pcb1
  1923.           {
  1924.           die "I'm dying...\n" ;
  1925.           }
  1926.  
  1927.       The mapping between the C callback and the Perl equivalent
  1928.       is stored in the global variable callback.
  1929.  
  1930.       This will be adequate    if you ever need to have only one
  1931.       callback registered at any time. An example could be an
  1932.       error    handler    like the code sketched out above. Remember
  1933.       though, repeated calls to register_fatal will    replace    the
  1934.       previously registered    callback function with the new one.
  1935.  
  1936.       Say for example you want to interface    to a library which
  1937.       allows asynchronous file i/o.     In this case you may be able
  1938.       to register a    callback whenever a read operation has
  1939.       completed. To    be of any use we want to be able to call
  1940.       separate Perl    subroutines for    each file that is opened.  As
  1941.       it stands, the error handler example above would not be
  1942.       adequate as it allows    only a single callback to be defined
  1943.       at any time. What we require is a means of storing the
  1944.       mapping between the opened file and the Perl subroutine we
  1945.       want to be called for    that file.
  1946.  
  1947.       Say the i/o library has a function asynch_read which
  1948.       associates a C function ProcessRead with a file handle fh -
  1949.       this assumes that it has also    provided some routine to open
  1950.       the file and so obtain the file handle.
  1951.  
  1952.           asynch_read(fh, ProcessRead)
  1953.  
  1954.       This may expect the C    _P_r_o_c_e_s_s_R_e_a_d function of    this form
  1955.  
  1956.           void
  1957.           ProcessRead(fh, buffer)
  1958.           int fh ;
  1959.           char *      buffer ;
  1960.           {
  1961.            ...
  1962.           }
  1963.  
  1964.       To provide a Perl interface to this library we need to be
  1965.       able to map between the fh parameter and the Perl subroutine
  1966.       we want called.  A hash is a convenient mechanism for
  1967.       storing this mapping.     The code below    shows a    possible
  1968.       implementation
  1969.  
  1970.           static HV    * Mapping = (HV*)NULL ;
  1971.  
  1972.  
  1973.  
  1974.  
  1975.  
  1976.  
  1977.      Page 30                        (printed 10/23/98)
  1978.  
  1979.  
  1980.  
  1981.  
  1982.  
  1983.  
  1984.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1985.  
  1986.  
  1987.  
  1988.           void
  1989.           asynch_read(fh, callback)
  1990.           int      fh
  1991.           SV *      callback
  1992.           CODE:
  1993.           /* If    the hash doesn't already exist,    create it */
  1994.           if (Mapping == (HV*)NULL)
  1995.               Mapping =    newHV()    ;
  1996.  
  1997.           /* Save the fh -> callback mapping */
  1998.           hv_store(Mapping, (char*)&fh,    sizeof(fh), newSVsv(callback), 0) ;
  1999.  
  2000.           /* Register with the C Library */
  2001.           asynch_read(fh, asynch_read_if) ;
  2002.  
  2003.       and asynch_read_if could look    like this
  2004.  
  2005.           static void
  2006.           asynch_read_if(fh, buffer)
  2007.           int fh ;
  2008.           char *      buffer ;
  2009.           {
  2010.           dSP ;
  2011.           SV **    sv ;
  2012.  
  2013.           /* Get the callback associated with fh */
  2014.           sv =    hv_fetch(Mapping, (char*)&fh , sizeof(fh), FALSE) ;
  2015.           if (sv == (SV**)NULL)
  2016.               croak("Internal error...\n") ;
  2017.  
  2018.           PUSHMARK(SP) ;
  2019.           XPUSHs(sv_2mortal(newSViv(fh))) ;
  2020.           XPUSHs(sv_2mortal(newSVpv(buffer, 0))) ;
  2021.           PUTBACK ;
  2022.  
  2023.           /* Call the Perl sub */
  2024.           perl_call_sv(*sv, G_DISCARD) ;
  2025.           }
  2026.  
  2027.       For completeness, here is asynch_close.  This    shows how to
  2028.       remove the entry from    the hash Mapping.
  2029.  
  2030.           void
  2031.           asynch_close(fh)
  2032.           int      fh
  2033.           CODE:
  2034.           /* Remove the    entry from the hash */
  2035.           (void) hv_delete(Mapping, (char*)&fh,    sizeof(fh), G_DISCARD) ;
  2036.  
  2037.           /* Now call the real asynch_close */
  2038.           asynch_close(fh) ;
  2039.  
  2040.  
  2041.  
  2042.  
  2043.      Page 31                        (printed 10/23/98)
  2044.  
  2045.  
  2046.  
  2047.  
  2048.  
  2049.  
  2050.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  2051.  
  2052.  
  2053.  
  2054.       So the Perl interface    would look like    this
  2055.  
  2056.           sub callback1
  2057.           {
  2058.           my($handle, $buffer) = @_ ;
  2059.           }
  2060.  
  2061.           #    Register the Perl callback
  2062.           asynch_read($fh, \&callback1) ;
  2063.  
  2064.           asynch_close($fh)    ;
  2065.  
  2066.       The mapping between the C callback and Perl is stored    in the
  2067.       global hash Mapping this time. Using a hash has the distinct
  2068.       advantage that it allows an unlimited    number of callbacks to
  2069.       be registered.
  2070.  
  2071.       What if the interface    provided by the    C callback doesn't
  2072.       contain a parameter which allows the file handle to Perl
  2073.       subroutine mapping?  Say in the asynchronous i/o package,
  2074.       the callback function    gets passed only the buffer parameter
  2075.       like this
  2076.  
  2077.           void
  2078.           ProcessRead(buffer)
  2079.           char *      buffer ;
  2080.           {
  2081.           ...
  2082.           }
  2083.  
  2084.       Without the file handle there    is no straightforward way to
  2085.       map from the C callback to the Perl subroutine.
  2086.  
  2087.       In this case a possible way around this problem is to
  2088.       predefine a series of    C functions to act as the interface to
  2089.       Perl,    thus
  2090.  
  2091.           #define MAX_CB          3
  2092.           #define NULL_HANDLE -1
  2093.           typedef void (*FnMap)() ;
  2094.  
  2095.           struct MapStruct {
  2096.           FnMap       Function ;
  2097.           SV *       PerlSub ;
  2098.           int       Handle ;
  2099.         } ;
  2100.  
  2101.           static void  fn1() ;
  2102.           static void  fn2() ;
  2103.           static void  fn3() ;
  2104.  
  2105.  
  2106.  
  2107.  
  2108.  
  2109.      Page 32                        (printed 10/23/98)
  2110.  
  2111.  
  2112.  
  2113.  
  2114.  
  2115.  
  2116.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  2117.  
  2118.  
  2119.  
  2120.           static struct MapStruct Map [MAX_CB] =
  2121.           {
  2122.               {    fn1, NULL, NULL_HANDLE },
  2123.               {    fn2, NULL, NULL_HANDLE },
  2124.               {    fn3, NULL, NULL_HANDLE }
  2125.           } ;
  2126.  
  2127.           static void
  2128.           Pcb(index, buffer)
  2129.           int index    ;
  2130.           char * buffer ;
  2131.           {
  2132.           dSP ;
  2133.  
  2134.           PUSHMARK(SP) ;
  2135.           XPUSHs(sv_2mortal(newSVpv(buffer, 0))) ;
  2136.           PUTBACK ;
  2137.  
  2138.           /* Call the Perl sub */
  2139.           perl_call_sv(Map[index].PerlSub, G_DISCARD) ;
  2140.           }
  2141.  
  2142.           static void
  2143.           fn1(buffer)
  2144.           char * buffer ;
  2145.           {
  2146.           Pcb(0, buffer) ;
  2147.           }
  2148.  
  2149.           static void
  2150.           fn2(buffer)
  2151.           char * buffer ;
  2152.           {
  2153.           Pcb(1, buffer) ;
  2154.           }
  2155.  
  2156.           static void
  2157.           fn3(buffer)
  2158.           char * buffer ;
  2159.           {
  2160.           Pcb(2, buffer) ;
  2161.           }
  2162.  
  2163.           void
  2164.           array_asynch_read(fh, callback)
  2165.           int          fh
  2166.           SV *      callback
  2167.           CODE:
  2168.           int index ;
  2169.           int null_index = MAX_CB ;
  2170.  
  2171.  
  2172.  
  2173.  
  2174.  
  2175.      Page 33                        (printed 10/23/98)
  2176.  
  2177.  
  2178.  
  2179.  
  2180.  
  2181.  
  2182.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  2183.  
  2184.  
  2185.  
  2186.           /* Find the same handle or an    empty entry */
  2187.           for (index = 0 ; index < MAX_CB ; ++index)
  2188.           {
  2189.               if (Map[index].Handle == fh)
  2190.               break    ;
  2191.  
  2192.               if (Map[index].Handle == NULL_HANDLE)
  2193.               null_index = index ;
  2194.           }
  2195.  
  2196.           if (index == MAX_CB && null_index == MAX_CB)
  2197.               croak ("Too many callback    functions registered\n") ;
  2198.  
  2199.           if (index == MAX_CB)
  2200.               index = null_index ;
  2201.  
  2202.           /* Save the file handle */
  2203.           Map[index].Handle = fh ;
  2204.  
  2205.           /* Remember the Perl sub */
  2206.           if (Map[index].PerlSub == (SV*)NULL)
  2207.               Map[index].PerlSub = newSVsv(callback) ;
  2208.           else
  2209.               SvSetSV(Map[index].PerlSub, callback) ;
  2210.  
  2211.           asynch_read(fh, Map[index].Function) ;
  2212.  
  2213.           void
  2214.           array_asynch_close(fh)
  2215.           int      fh
  2216.           CODE:
  2217.           int index ;
  2218.  
  2219.           /* Find the file handle */
  2220.           for (index = 0; index    < MAX_CB ; ++ index)
  2221.               if (Map[index].Handle == fh)
  2222.               break    ;
  2223.  
  2224.           if (index == MAX_CB)
  2225.               croak ("could not    close fh %d\n",    fh) ;
  2226.  
  2227.           Map[index].Handle = NULL_HANDLE ;
  2228.           SvREFCNT_dec(Map[index].PerlSub) ;
  2229.           Map[index].PerlSub = (SV*)NULL ;
  2230.  
  2231.           asynch_close(fh) ;
  2232.  
  2233.       In this case the functions fn1, fn2, and fn3 are used    to
  2234.       remember the Perl subroutine to be called. Each of the
  2235.       functions holds a separate hard-wired    index which is used in
  2236.       the function Pcb to access the Map array and actually    call
  2237.       the Perl subroutine.
  2238.  
  2239.  
  2240.  
  2241.      Page 34                        (printed 10/23/98)
  2242.  
  2243.  
  2244.  
  2245.  
  2246.  
  2247.  
  2248.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  2249.  
  2250.  
  2251.  
  2252.       There    are some obvious disadvantages with this technique.
  2253.  
  2254.       Firstly, the code is considerably more complex than with the
  2255.       previous example.
  2256.  
  2257.       Secondly, there is a hard-wired limit    (in this case 3) to
  2258.       the number of    callbacks that can exist simultaneously. The
  2259.       only way to increase the limit is by modifying the code to
  2260.       add more functions and then recompiling.  None the less, as
  2261.       long as the number of    functions is chosen with some care, it
  2262.       is still a workable solution and in some cases is the    only
  2263.       one available.
  2264.  
  2265.       To summarize,    here are a number of possible methods for you
  2266.       to consider for storing the mapping between C    and the    Perl
  2267.       callback
  2268.  
  2269.       1. Ignore the    problem    - Allow    only 1 callback
  2270.            For a lot of situations,    like interfacing to an error
  2271.            handler,    this may be a perfectly    adequate solution.
  2272.  
  2273.       2. Create a sequence of callbacks - hard wired limit
  2274.            If it is    impossible to tell from    the parameters passed
  2275.            back from the C callback    what the context is, then you
  2276.            may need    to create a sequence of    C callback interface
  2277.            functions, and store pointers to    each in    an array.
  2278.  
  2279.       3. Use a parameter to    map to the Perl    callback
  2280.            A hash is an ideal mechanism to store the mapping
  2281.            between C and Perl.
  2282.  
  2283.       AAAAlllltttteeeerrrrnnnnaaaatttteeee SSSSttttaaaacccckkkk MMMMaaaannnniiiippppuuuullllaaaattttiiiioooonnnn
  2284.  
  2285.       Although I have made use of only the POP* macros to access
  2286.       values returned from Perl subroutines, it is also possible
  2287.       to bypass these macros and read the stack using the ST macro
  2288.       (See the _p_e_r_l_x_s manpage for a    full description of the    ST
  2289.       macro).
  2290.  
  2291.       Most of the time the POP* macros should be adequate, the
  2292.       main problem with them is that they force you    to process the
  2293.       returned values in sequence. This may    not be the most
  2294.       suitable way to process the values in    some cases. What we
  2295.       want is to be    able to    access the stack in a random order.
  2296.       The ST macro as used when coding an XSUB is ideal for    this
  2297.       purpose.
  2298.  
  2299.       The code below is the    example    given in the section _R_e_t_u_r_n_i_n_g
  2300.       _a _l_i_s_t _o_f _v_a_l_u_e_s recoded to use ST instead of    POP*.
  2301.  
  2302.  
  2303.  
  2304.  
  2305.  
  2306.  
  2307.      Page 35                        (printed 10/23/98)
  2308.  
  2309.  
  2310.  
  2311.  
  2312.  
  2313.  
  2314.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  2315.  
  2316.  
  2317.  
  2318.           static void
  2319.           call_AddSubtract2(a, b)
  2320.           int a ;
  2321.           int b ;
  2322.           {
  2323.           dSP ;
  2324.           I32 ax ;
  2325.           int count ;
  2326.  
  2327.           ENTER    ;
  2328.           SAVETMPS;
  2329.  
  2330.           PUSHMARK(SP) ;
  2331.           XPUSHs(sv_2mortal(newSViv(a)));
  2332.           XPUSHs(sv_2mortal(newSViv(b)));
  2333.           PUTBACK ;
  2334.  
  2335.           count    = perl_call_pv("AddSubtract", G_ARRAY);
  2336.  
  2337.           SPAGAIN ;
  2338.           SP -=    count ;
  2339.           ax = (SP - PL_stack_base) + 1    ;
  2340.  
  2341.           if (count != 2)
  2342.               croak("Big trouble\n") ;
  2343.  
  2344.           printf ("%d +    %d = %d\n", a, b, SvIV(ST(0))) ;
  2345.           printf ("%d -    %d = %d\n", a, b, SvIV(ST(1))) ;
  2346.  
  2347.           PUTBACK ;
  2348.           FREETMPS ;
  2349.           LEAVE    ;
  2350.           }
  2351.  
  2352.       Notes
  2353.  
  2354.       1.   Notice that it was necessary to define the variable ax.
  2355.            This is because the ST macro expects it to exist.  If
  2356.            we were in an XSUB it would not be necessary to define
  2357.            ax as it    is already defined for you.
  2358.  
  2359.       2.   The code
  2360.  
  2361.                SPAGAIN ;
  2362.                SP -= count ;
  2363.                ax = (SP    - PL_stack_base) + 1 ;
  2364.  
  2365.            sets the    stack up so that we can    use the    ST macro.
  2366.  
  2367.       3.   Unlike the original coding of this example, the
  2368.            returned    values are not accessed    in reverse order.  So
  2369.            ST(0) refers to the first value returned    by the Perl
  2370.  
  2371.  
  2372.  
  2373.      Page 36                        (printed 10/23/98)
  2374.  
  2375.  
  2376.  
  2377.  
  2378.  
  2379.  
  2380.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  2381.  
  2382.  
  2383.  
  2384.            subroutine and ST(count-1) refers to the    last.
  2385.  
  2386.       CCCCrrrreeeeaaaattttiiiinnnngggg aaaannnndddd ccccaaaalllllllliiiinnnngggg aaaannnn aaaannnnoooonnnnyyyymmmmoooouuuussss ssssuuuubbbbrrrroooouuuuttttiiiinnnneeee iiiinnnn CCCC
  2387.  
  2388.       As we've already shown, perl_call_sv can be used to invoke
  2389.       an anonymous subroutine.  However, our example showed    how
  2390.       Perl script invoking an XSUB to preform this operation.
  2391.       Let's    see how    it can be done inside our C code:
  2392.  
  2393.        ...
  2394.  
  2395.        SV *cvrv = perl_eval_pv("sub    { print    'You will not find me cluttering any namespace!' }", TRUE);
  2396.  
  2397.        ...
  2398.  
  2399.        perl_call_sv(cvrv, G_VOID|G_NOARGS);
  2400.  
  2401.       perl_eval_pv is used to compile the anonymous    subroutine,
  2402.       which    will be    the return value as well (read more about
  2403.       perl_eval_pv in the perl_eval_pv entry in the    _p_e_r_l_g_u_t_s
  2404.       manpage).  Once this code reference is in hand, it can be
  2405.       mixed    in with    all the    previous examples we've    shown.
  2406.  
  2407.      SSSSEEEEEEEE AAAALLLLSSSSOOOO
  2408.       the _p_e_r_l_x_s manpage, the _p_e_r_l_g_u_t_s manpage, the    _p_e_r_l_e_m_b_e_d
  2409.       manpage
  2410.  
  2411.      AAAAUUUUTTTTHHHHOOOORRRR
  2412.       Paul Marquess    <_p_m_a_r_q_u_e_s_s@_b_f_s_e_c._b_t._c_o._u_k>
  2413.  
  2414.       Special thanks to the    following people who assisted in the
  2415.       creation of the document.
  2416.  
  2417.       Jeff Okamoto,    Tim Bunce, Nick    Gianniotis, Steve Kelem,
  2418.       Gurusamy Sarathy and Larry Wall.
  2419.  
  2420.      DDDDAAAATTTTEEEE
  2421.       Version 1.3, 14th Apr    1997
  2422.  
  2423.  
  2424.  
  2425.  
  2426.  
  2427.  
  2428.  
  2429.  
  2430.  
  2431.  
  2432.  
  2433.  
  2434.  
  2435.  
  2436.  
  2437.  
  2438.  
  2439.      Page 37                        (printed 10/23/98)
  2440.  
  2441.  
  2442.  
  2443.  
  2444.  
  2445.  
  2446.      PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  2447.  
  2448.  
  2449.  
  2450.  
  2451.  
  2452.  
  2453.  
  2454.  
  2455.  
  2456.  
  2457.  
  2458.  
  2459.  
  2460.  
  2461.  
  2462.  
  2463.  
  2464.  
  2465.  
  2466.  
  2467.  
  2468.  
  2469.  
  2470.  
  2471.  
  2472.  
  2473.  
  2474.  
  2475.  
  2476.  
  2477.  
  2478.  
  2479.  
  2480.  
  2481.  
  2482.  
  2483.  
  2484.  
  2485.  
  2486.  
  2487.  
  2488.  
  2489.  
  2490.  
  2491.  
  2492.  
  2493.  
  2494.  
  2495.  
  2496.  
  2497.  
  2498.  
  2499.  
  2500.  
  2501.  
  2502.      Page 38                        (printed 10/23/98)
  2503.  
  2504.  
  2505.  
  2506.  
  2507.  
  2508.  
  2509.